<!-- 带扫描的搜索 -->
<template lang="pug">
g-h(j-c="space-between" a-i="center")
  div.search
    input.search-area(
        ref="search"
        :placeholder="placeholder"
        @keyup.enter="search"
        @focus="searchHasFocus = true"
        @blur="searchHasFocus = false"
        v-model="searchValue"
        )
    icon-search.icon-search(width="20" strokeWidth="9")
    icon-cross.icon-cross(
        fill="#e0e0e0"
        stroke="#eeeeee"
        v-show="searchValue != '' && searchHasFocus"
        @click.native="clear"
        )

  img.scan(src="img/scan.svg" @click="scan" width="30")
</template>

<script>
/*
  事件
    search    搜索
    scan      扫描
*/

import util from "$util"

export default {
  name: "ScanSearch",
  props: {
    // 搜索输入框没点击时默认显示的内容
    placeholder: {
      type: String,
      default: "",
    },
    // 搜索输入框的默认值
    initSearchValue: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      searchValue: this.initSearchValue,
      searchHasFocus: false,
    }
  },
  watch: {
    initSearchValue(v) {
      this.searchValue = v
    },
  },

  methods: {
    search(e) {
      this.$emit("search", e.target.value)
      this.$refs.search.blur()
    },
    clear() {
      this.searchValue = ""
    },
    scan() {
      let onSuccess = (result) => {
        this.searchValue = result.text
        this.$emit("scan", result.text)
        /* util.Toast(`
          Result: ${result.text},
          Format: ${result.format}
        `) */
      }

      let onError = (error) => {
        console.log("scan failed: ${error}")
      }

      let option = {
        disableSuccessBeep: true,
      }

      cordova.plugins.barcodeScanner.scan(onSuccess, onError, option)
    },
  },

  mounted() {
    if (!util.useScanPlugin) {
      this.$refs.search.focus()
    }
  },
}
</script>

<style lang="stylus" scoped>

.c-root
  padding: 0.6rem 1rem

.search
  position: relative
  width: 100%

.scan
  margin-left: 1rem

.search-area
  resize: none
  padding: 0.3rem 2rem
  width: 100%
  border-style: none
  border-radius: 5px
  outline: none

.icon-search
  position: absolute
  top: 50%
  transform: translateY(-50%)
  left: 0.3rem
  color: grey500

.icon-cross
  position: absolute
  top: 50%
  transform: translateY(-50%)
  right: 0.3rem
  color: grey600

</style>
